<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { RequestPath, startRequest, GoodsItemData, GoodsResponseData } from '../base/RequestWork';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
const props = defineProps(['keyword'])
// 路由管理对象
let router = useRouter()
// 商品数据
let goods = ref()
// 分页参数
let offset = 0
const limit = 4
// 是否有更多数据
let hasMore = ref(true)
// 页面挂载时加载数据
onMounted(()=>{
    loadGoods()
})
// 请求商品数据
function loadGoods() {
    // 调用搜索接口
    startRequest(RequestPath.goodsListSearch, 'get', {'keyword': props.keyword, offset, limit}).then((response)=>{
        let data = response.data as GoodsResponseData
        let datas:GoodsItemData[] = goods.value ?? []
        // 判断返回的数据量是否小于limit，小于则表明没有更多数据了
        hasMore.value = (data.datas ?? []).length >= limit
        // 将返回的数据追加到数据源中
        datas.push(...(data.datas ?? []))
        goods.value = datas
        // 对offset进行设置
        offset = datas.length
    }).catch((error)=>{
        ElMessage.error({
            message: error.response.data.error
        })
    })
}

// 跳转到商品详情页
function goDetail(item: GoodsItemData) {
    router.push({
        name: 'goodsDetail',
        params: {id: item.id}
    })
}

</script>
<template>
    <!-- 空态组件 -->
    <el-empty description="无相关商品" v-show="goods?.length == 0"/>
    <!-- 搜索结果列表 -->
    <div class="goods_list">
        <div v-for="item in goods" class="goods_item" @click="goDetail(item)">
            <div style="width: 200px; height: 150px; overflow: hidden; ">
                <el-image style="width: 100%; height: 100%;" :src="item.image" fit="fill" />
            </div>
            <div style="width: 100%; height: 150px; background-color: #eeeeee; position: relative;">
                <div style="padding: 5px;"><span class="brend">{{ item.brand }}</span>{{ item.name }}</div>
                <div style="padding-left: 5px;padding-right: 5px; font-size: 13px; color: gray;">{{ item.description }}</div>
                <div style="padding: 5px; font-size: 18px; color: red;">惊喜价:{{ item.price }}￥ <span style="color: gray; font-size: 11px;">原价:{{ item.discounted_price }}￥</span></div>
                <el-tag style="position: absolute; bottom: 10px; left:10px" :type="item.status == 1 ? 'success' : 'error'">{{ item.status == 1 ? '售卖中' : '已下架' }}</el-tag>
            </div>
        </div>
        <div v-show="hasMore" style="width: 100%; text-align: center; margin-top: 15px; color: grey;" @click="loadGoods">点击加载更多</div>
    </div>
</template>